package eolympics;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import minigames.IMiniGame;

public class MiniGamePluginsLoader
{
    private final File          mMiniGamesFolder;
    private final static String MINI_GAME_MAIN_CLASS_NAME = "MiniGameMain";

    public MiniGamePluginsLoader(final File pMiniGamesFolder)
    {
        mMiniGamesFolder = pMiniGamesFolder;
    }

    public List<IMiniGame> loadMiniGamePlugins()
    {
        List<IMiniGame> miniGames = new ArrayList<>();

        for( File folderInMiniGamesFolder : mMiniGamesFolder.listFiles() )
        {
            if( !folderInMiniGamesFolder.isDirectory() )
            {
                continue;
            }

            for( File potentialMiniGame : folderInMiniGamesFolder.listFiles() )
            {
                if( !potentialMiniGame.getName().equals(MINI_GAME_MAIN_CLASS_NAME + ".class") )
                {
                    continue;
                }

                ClassLoader urlClassloader = null;
                try
                {
                    URL url = potentialMiniGame.toURI().toURL();
                    URL[] urls = new URL[] { url };
                    urlClassloader = new URLClassLoader(urls);
                    String className = folderInMiniGamesFolder.getName() + "." + MINI_GAME_MAIN_CLASS_NAME;
                    Class miniGameClass = urlClassloader.loadClass(className);
                    
                    IMiniGame miniGame = (IMiniGame)miniGameClass.newInstance();
                    miniGames.add(miniGame);
                }
                catch( Exception e )
                {
                    System.out.println("could not load minigame!");
                    e.printStackTrace();
                }
            }
        }

        return miniGames;
    }
}
